//
//  DKPhotoView.swift
//  Sina
//
//  Created by 赵柏清 on 16/8/4.
//  Copyright © 2016年 DarkZhao. All rights reserved.
//

import UIKit
import SDWebImage

/// view之间的间距
private let DKPhotoViewMargin : CGFloat = 10
/// item之间的间距
private let DKPhotoItemMargin : CGFloat = 10
/// item的宽和高
private let DKPhotoItemWH = (UIScreen.mainScreen().bounds.width - 2 * DKPhotoViewMargin - 2 * DKPhotoItemMargin) / 3
/// 重用标示
private let reuserIdentifier = "PhotoCell"

class DKPhotoView: UICollectionView {
    
    /// 定义一个数组,来接收数据
    var pic_urls : [DKPhotoModel]? {
        didSet {
            
            let viewSize = calculateViewSize()
            
            self.snp_updateConstraints { (make) -> Void in
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
            }
            reloadData()
        }
    }
    
    private func calculateViewSize()->CGSize{
        
        guard let count = pic_urls?.count else {
            return CGSizeZero
        }
        
        if count == 1 {
            
            let key = pic_urls!.first!.thumbnail_pic!
            
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            // 判断图片是否真的能够取出
            if image != nil {
                var imageSize = image.size
                
                // 过窄处理
                if imageSize.width < 80 {
                    let width : CGFloat = 80
                    let height = imageSize.height * width / imageSize.width
                    
                    imageSize.width = width
                    imageSize.height = height > 150 ? 150 : height
                } else if imageSize.width > 200 {
                    // 过宽处理
                    let width: CGFloat = 200
                    let height = imageSize.height * width / imageSize.width
                    
                    imageSize.width = width
                    imageSize.height = height
                    
                }
                
                flowLayout.itemSize = imageSize
                
                return imageSize
            } else {
                flowLayout.itemSize = CGSizeMake(DKPhotoItemWH, DKPhotoItemWH)
            }
            
        }
        
        if count == 4 {
            
            let wh = DKPhotoItemWH * 2 + DKPhotoItemMargin
            
            return CGSizeMake(wh, wh)
        }
        
        if count == 2 || count == 3 {
            
            
            return CGSizeMake(UIScreen.mainScreen().bounds.width - 2 * DKPhotoViewMargin, DKPhotoItemWH)
        }

        if count == 5 || count == 6 {
            
            return CGSizeMake(UIScreen.mainScreen().bounds.width - 2 * DKPhotoViewMargin, (DKPhotoItemWH + DKPhotoItemMargin ) * 2 )
            
        }
        
        if count == 7 || count == 8 || count == 9 {
            return CGSizeMake(UIScreen.mainScreen().bounds.width - 2 * DKPhotoViewMargin, (DKPhotoItemWH + DKPhotoItemMargin ) * 3 )
            
        }
        
        return CGSizeZero
    }
    
    /// 流布局
    let flowLayout : UICollectionViewFlowLayout = {
        let flow = UICollectionViewFlowLayout()
//        flow.itemSize = CGSizeMake(DKPhotoItemWH,DKPhotoItemWH)
//        flow.minimumLineSpacing = DKPhotoItemMargin
//        flow.minimumInteritemSpacing = DKPhotoItemMargin
        return flow
    }()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        // 注册cell
        registerClass(DKPhotoCell.self, forCellWithReuseIdentifier: reuserIdentifier)
        dataSource = self
        
        flowLayout.itemSize = CGSizeMake(DKPhotoItemWH,DKPhotoItemWH)
        flowLayout.minimumInteritemSpacing = DKPhotoItemMargin
        flowLayout.minimumLineSpacing = DKPhotoItemMargin
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: collectionView代理方法的实现
extension DKPhotoView : UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuserIdentifier, forIndexPath: indexPath) as! DKPhotoCell
        
        cell.cellModel = pic_urls![indexPath.item]
        
        return cell
    }
    
}


// MARK: photo的cell
class DKPhotoCell : UICollectionViewCell {
    /// cell的模型
    var cellModel : DKPhotoModel? {
        didSet {
            cellImageView.sd_setImageWithURL(NSURL(string: cellModel?.thumbnail_pic ?? ""))
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 布局子控件
    private func setupUI(){
        contentView.addSubview(cellImageView)
        cellImageView.snp_makeConstraints { (make) -> Void in
//            make.left.top.right.bottom.equalTo(contentView)
            make.edges.equalTo(contentView.snp_edges).offset(0)
        }
    }
    
    
    // MARK: 懒加载子控件
    /// cell显示的图片
    private lazy var cellImageView : UIImageView = UIImageView()
    
}